package com.xijitech.glx;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;

import com.facebook.react.ReactActivity;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.modules.core.PermissionListener;
import com.tbruyelle.rxpermissions.RxPermissions;

import rx.schedulers.Schedulers;

public class RNBridgeModule extends ReactContextBaseJavaModule {
    private final ReactApplicationContext reactContext;

    public RNBridgeModule(ReactApplicationContext reactContext) {
        super(reactContext);
        this.reactContext = reactContext;
    }

    @Override
    public String getName() {
        return "RNBridgeModule";
    }

    @ReactMethod
    public void getSystemModel(Callback callback) {
        callback.invoke(SystemUtil.getSystemModel());
    }

    @ReactMethod
    public void canOpenSettings(Promise promise) {
        promise.resolve(true);
    }

    @ReactMethod
    public void openSettings() {
        final Intent i = new Intent();
        i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        i.addCategory(Intent.CATEGORY_DEFAULT);
        i.setData(Uri.parse("package:" + this.reactContext.getPackageName()));
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        this.reactContext.startActivity(i);
    }

    @ReactMethod
    public void preStartCall(final String number) {
        reactContext.getCurrentActivity().runOnUiThread(() -> new RxPermissions(reactContext.getCurrentActivity())
                // Ask for permissions when button is clicked
                .request(Manifest.permission.CALL_PHONE)
                .subscribeOn(Schedulers.io())
                .subscribe(granted -> {
                    if (granted) {
                        Intent intent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + number));
                        reactContext.getCurrentActivity().startActivity(intent);
                    } else {
                        ToastUtil.show(reactContext, "电话拨打失败");
                    }

                }));
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    @ReactMethod
    public void checkPermission(final Promise promise) {
        Activity activity = reactContext.getCurrentActivity();
        final int writePermission = ActivityCompat
                .checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        final int cameraPermission = ActivityCompat
                .checkSelfPermission(activity, Manifest.permission.CAMERA);

        final boolean permissionsGrated = writePermission == PackageManager.PERMISSION_GRANTED &&
                cameraPermission == PackageManager.PERMISSION_GRANTED;
        if (!permissionsGrated) {
            final Boolean dontAskAgain = ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) && ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.CAMERA);
            final Boolean askAgain = !ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) && !ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.CAMERA);
            if (dontAskAgain || (askAgain && (writePermission + cameraPermission == PackageManager.PERMISSION_DENIED))) {
                promise.resolve(false);
            } else {
                String[] PERMISSIONS = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
                ((ReactActivity) activity).requestPermissions(PERMISSIONS, 14005, new PermissionListener() {
                    @Override
                    public boolean onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
                        boolean permissionsGranted = true;
                        for (int i = 0; i < permissions.length; i++) {
                            final boolean granted = grantResults[i] == PackageManager.PERMISSION_GRANTED;
                            permissionsGranted = permissionsGranted && granted;
                        }

                        if (!permissionsGranted) {
                            ToastUtil.show(reactContext, "打开相册和相机访问权限，才能正常上传");
                            return false;
                        }
                        promise.resolve(true);
                        return true;
                    }
                });
            }
        } else {
            promise.resolve(true);
        }
    }


    /**
     * 跳转到设置-允许安装未知来源-页面
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startInstallPermissionSettingActivity() {
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        reactContext.startActivity(intent);
    }
}
